//
//  Account.m
//  YuchBox
//
//  Created by Ivan on 11-11-10.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Account.h"
#import "Utility.h"
#import "SingletonClassGenerator.h"

typedef enum {
    DBUid        = 0,
    DBHost,
    DBPort,
    DBPassword,
    DBTimestamp,
    DBAutoLogin,
} DBEmailFieldIndex;

@implementation Account
//SYNTHESIZE_SINGLETON_FOR_CLASS(Account);

- (id)initSingleton
{
    self = [self init];
    
    return  self;
}

@synthesize uid         = _uid;
@synthesize host        = _host;
@synthesize port        = _port;
@synthesize password    = _password;
@synthesize timestamp   = _timestamp;
@synthesize isAutoLogin = _isAutoLogin;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (void)save:(IvanSqliteDB *)con
{
    if (![con checkConnection]) {
        [con connect];
    }
    
    NSString *sql;
    Account *account = [[Account alloc] init];
    [Account retrieveAccount:con account:account withHost:_host withPort:_port withPassword:_password];

    if (0 == account.uid) {
        sql = [NSString stringWithFormat:@"INSERT INTO Account VALUES( \
               null, '%@', %d, '%@', '%llu', \
               %d)",
               // id, auto increase
               _host, _port, _password, _timestamp,
               _isAutoLogin];
    } else {
        sql = [NSString stringWithFormat:@"UPDATE Account SET host = '%@', \
                        port = %d, password_des = '%@', \
                        timestamp = %llu, auto_login = %d WHERE id = %llu",
                        account.host, account.port, account.password,
                        _timestamp, _isAutoLogin,
                        account.uid];
    }

    if (![con insertWithSql:sql]) {
        TTLOGF_ERROR(@"insert Account(%@) error!", _host);
        [account release];
        return;
    }
    
    [account release];
    _uid = [con getLastInsertRowid];
}

+ (void)getOneAccountWith:(sqlite3_stmt *)stmt account:(Account *)account
{    
    account.uid         = (UInt64)sqlite3_column_int64(stmt, DBUid);
    char *host_c        = (char*)sqlite3_column_text(stmt, DBHost);
    account.host        = [NSString stringWithUTF8String:(NULL == host_c ? "" : host_c)];
    account.port        = (UInt32)sqlite3_column_int(stmt, DBPort);
    char *password_c    = (char*)sqlite3_column_text(stmt, DBPassword);
    account.password    = [NSString stringWithUTF8String:(NULL == password_c ? "" : password_c)];
    account.timestamp   = (UInt64)sqlite3_column_int64(stmt, DBTimestamp);
    account.isAutoLogin = (UInt32)sqlite3_column_int64(stmt, DBAutoLogin);
}

+ (void)retrieveAccounts:(IvanSqliteDB *)con accounts:(NSMutableArray *)accounts limit:(NSInteger)limit
{
    if (nil == con || ![con checkConnection]) {
        [con connect];
    }
    
    // NSMutableArray *emails = [[NSMutableArray alloc] init];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM account WHERE auto_login = 1 ORDER BY timestamp DESC limit %d", limit];
    sqlite3_stmt *stmt = [con prepareSelect:sql];

    while (SQLITE_ROW == sqlite3_step(stmt)) {
        Account *account    = [[Account alloc] init];
        [Account getOneAccountWith:stmt account:account];
        [accounts addObject:account];
        [account release];
    } 
}

+ (void)retrieveAccount:(IvanSqliteDB *)con account:(Account *)account withPkId:(UInt64)pkId
{
    if (nil == con || ![con checkConnection]) {
        [con connect];
    }
    
    NSString *sql = [NSString stringWithFormat:@"SELECT id FROM Account WHERE id = %llu", pkId];
    
    sqlite3_stmt *stmt = [con prepareSelect:sql];
    if (SQLITE_ROW == sqlite3_step(stmt)) {
//        Account *account = [[Account alloc] init];
        [Account getOneAccountWith:stmt account:account];
    }
}

+ (void)retrieveAccount:(IvanSqliteDB *)con account:(Account *)account withHost:(NSString *)host withPort:(NSInteger)port withPassword:(NSString *)password
{
    if (nil == con || ![con checkConnection]) {
        [con connect];
    }
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM account WHERE host = '%@' and port = %d and password_des = '%@' ", 
                     host, 
                     port, 
                     password];
    
    sqlite3_stmt *stmt = [con prepareSelect:sql];
    //     NSLog(@"%@",sql);
    if (SQLITE_ROW == sqlite3_step(stmt)) {
        [Account getOneAccountWith:stmt account:account];
    } else {
        account.uid = 0;
    }
}

+ (void)getLastLoginAccount:(IvanSqliteDB *)con account:(Account*)account withTimeoutInterval:(UInt64)timeout
{
    if (nil == con || ![con checkConnection]) {
        [con connect];
    }
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM account WHERE (strftime('%%s','now') - timestamp < %llu) ORDER BY timestamp DESC limit 1", timeout];
    
    sqlite3_stmt *stmt = [con prepareSelect:sql];
    //     NSLog(@"%@",sql);
    if (SQLITE_ROW == sqlite3_step(stmt)) {
        [Account getOneAccountWith:stmt account:account];
    } else {
        account.uid = 0;
    }
    
}
//+ (Account *)getLastLogin

@end
